/**
 * jQuery Hmusic
 * A very lightweight jQuery plugin to play music
 * http://ziiber.me
 *
 * Licensed under the MIT license.
 * Copyright 2015 Ziiber
 * https://github.com/ziiber
 */;
 (function($, window){
    $('body').append( '<div id="HmusicTips" class="HmusicTips"></div>' );

    /* Ziiber - 提示插件 */
    $.extend({
        HmusicTips:function( content, time )
        {
            var self = $('#HmusicTips');
            var time = time ? time:3000;

            if( self.hasClass('active') )
                clearTimeout( $.Htips_hwnd );

            self.text(content);
            self.addClass('active');
            $.Htips_hwnd = setTimeout( function(){ self.removeClass('active'); }, time );
        }
    });

    /* localstorage - ziiber */
    var Storage = {
        setItem:function( key, data ){
            localStorage.setItem( key, data );
        },
        getItem:function( key ){
            var value = localStorage.getItem( key );
            return value;
        },
        setJson:function( key, data ){
            localStorage.setItem( key, JSON.stringify(data) );
        },
        getJson:function( key ){
            var value = window.localStorage.getItem( key );
            return JSON.parse( value );
        },
        clear:function( key ){
            if( key )
                window.localStorage.removeItem( key );
            else
                window.localStorage.clear();
        },
        has:function( key ){
            return window.localStorage.hasOwnProperty( key );
        },
        removeKeys:function( key ){
            // 删除前缀为 key 的键
            var list = [];
            for( var i = 0; i < localStorage.length; i++ )
            {
                var str = localStorage.key(i).substr( 0, key.length );
                if( str == key )
                    list.push( localStorage.key(i) );
            }

            for( var i=0; i<list.length; i++ )
            {
                localStorage.removeItem( list[i] );
            }
        }
    };

    /* HTTP - ziiber */
    var HTTP = {
        apiHost:'http://api.ziiber.me',
        appid: '',
        secret: '',
        token:'',
        expires:0,
        request:function( url, method, params, success, error, async, cache, host )
        {
            method = method || 'get';
            cache  = cache  || false;
            host   = host   || 1;
            params = params || null;
            async  = async  || true;

            var options = {};

            if( host == 1 )
                options.url = this.apiHost + url;
            else
                options.url = url;

            options.data     = params;
            options.method   = method;
            options.cache    = cache;
            options.async    = async;
            options.dataType = 'json';
            options.crossDomain = true;
            

            // 获取token
            this.getToken();
            options.headers = { 'token': this.token, 'appid': this.appid };


            options.success = function( data, status, xhr ){
                if( typeof(success) == 'function' )
                    success( data, status, xhr );
            }

            options.error = function(xhr, status, message){
                if( typeof error === 'function' ){
                    error( xhr.responseJSON, message, status );
                    $.HmusicTips( '数据获取失败...' );
                }
            };

            $.ajax(options);
        },
        getToken: function( self )
        {
            var token   = Storage.getItem('token') || false;
            var expires = Storage.getItem('expires') || 0;

            var date = new Date();
            var time = Math.floor( date.getTime() / 1000 );

            // console.log( 'Token过期时间：' + expires);
            // console.log( '当前时间：' + time );
            // console.log( '过期：' + (expires < (time+600)) );

            if( token == false || expires < (time + 600) )
            {
                var query = { 
                    url: this.apiHost + '/Auth/token', 
                    method: 'get', 
                    async: false, 
                    dataType: 'json', 
                    data: { 
                        secret: this.secret,
                        appid: this.appid
                    },
                    success: function( data )
                    {
                        if( data.code == 0 )
                        {
                            HTTP.token   = data.value.token;
                            HTTP.expires = data.value.expires;
                            Storage.setItem('token', data.value.token);
                            Storage.setItem('expires', data.value.expires);
                        }
                    }
                };

                $.ajax(query);
            }
            else
            {
                HTTP.token   = token;
                HTTP.expires = expires;
            }
        }
    };

    /* 图片预加载 */
    function loadImage( src, success, error )
    {
        var img = new Image();

        img.onload = function()
        {
            if( typeof(success) == 'function' )
                success( img );
        };

        img.onerror = function()
        {
            if( typeof(error) == 'function' )
                error( img );
        };

        img.src = src;
    }

    var Hmusic = function( ele, opt )
    {
        var self = $(this);

        /* 当前jquery对象 */
        self.$element = ele;

        /* 默认配置 */
        /* Model: 1.列表 2.随机 3.单曲 */
        self.defaults = { 
            model: 1, 
            // autoplay: false, 
            loop: true, 
            preload: 'metadata',
            volume: 0.4,
            openLrc: 1
        };
        /*
        auto – 当页面加载后载入整个音频
        metadata – 当页面加载后只载入元数据
        none – 当页面加载后不载入音频
        */
    
        /* 播放器配置 */
        self.options = $.extend( {}, self.defaults, opt );

        if( self.options.appid )
            HTTP.appid = self.options.appid;
        else
            $.HmusicTips( 'Appid不存在！' );

        if( self.options.secret )
            HTTP.secret = self.options.secret;
        else
            $.HmusicTips( 'Secret不存在！' );

        // 播放器运行时
        self.runtime = {
            // 专辑索引 0
            album:{
                last:-1,  // 上一次播放专辑 -1为无
                index:-1, // 当前进入的专辑
                active:-1 // 正在播放的专辑
            },
            // 正在播放的歌曲索引
            music:{
                last:-1, // 上一首
                index:-1 // 当前播放
            },
            lrc:false
        };

        /* UI设置 - 禁止选中 */
        self.$element[0].onselectstart = function(){ return false; };

        /* Music对象 */
        self.audio = new Audio();

        // 设置 Audio
        for( var item in self.options )
            self.audio[item] = self.options[item];

        /* 挂接事件 */
        self.listenEvent = function( type, e )
        {
            /*
            loadstart       //客户端开始请求数据
            progress        //客户端正在请求数据
            suspend         //延迟下载
            abort           //客户端主动终止下载（不是因为错误引起），
            error           //请求数据时遇到错误
            stalled         //网速失速
            play            //play()和autoplay开始播放时触发
            pause           //pause()触发
            loadedmetadata  //成功获取资源长度
            loadeddata      //
            waiting         //等待数据，并非错误
            playing         //开始回放
            canplay         //可以播放，但中途可能因为加载而暂停
            canplaythrough  //可以播放，歌曲全部加载完毕
            seeking         //寻找中
            seeked          //寻找完毕
            timeupdate      //播放时间改变
            ended           //播放结束
            ratechange      //播放速率改变
            durationchange  //资源长度改变
            volumechange    //音量改变
            */
            if( typeof(e) == 'function' )
            {
                if( window.addEventListener )
                    self.audio.addEventListener(type, e);
                else
                    self.audio.attachEvent( type, e );
            }
        };

        // 取随机数
        function randoms( n, m )
        {
            var c = m - n + 1;  
            return Math.floor(Math.random() * c + n);
        }

        /* 时间转换 - 秒到时分 */
        self.audio.time_s2m = function(s, c, hour)
        {
            c = c ? c : ':'; // 连接符号

            // 计算
            var h = 0, i = 0, arr = [];
            if( s > 60 )
            {
                i = parseInt( s / 60 );
                s = parseInt( s % 60 );
                if( i > 60 ) 
                {
                    h = parseInt(i/60);
                    i = parseInt(i%60);
                }
            }

            // 补零
            var zero = function(v){
                return ( v>>0 ) < 10 ? "0"+v : v;
            };

            if( hour )
                arr = [zero(h),zero(i),zero(s)];
            else
                arr = [zero(i),zero(s)];
            
            return arr.join(c);
        };

        /**
         * 歌词解析
         * @param  {[type]} lrc lrc歌词
         * @param  {[type]} ms  精确到毫秒  默认false
         * @return {[type]}     返回lrc信息对象
         */
        self.analysisLrc = function(lrc, ms)
        {
            var lrcLine = []; // 行数组
            var lineSum = 0; // 总行数
            var regexpLineTime    = /\[(\d{2})\:(\d{0,2})([\:|\.](\d{0,5})){0,1}\]/gi; // 匹配行时间
            var regexpLineTimeArr = /\[(\d{2})\:(\d{0,2})([\:|\.](\d{0,5}))?\]/; // 匹配时间子元素

            var regexpLineText = /\](?!\[)(.*)/; // 匹配歌词
            var lrcLineTimeArr = [], lrcLineTime = [], lrcLineText = '';

            var lrcObj = {
                ti:'',      // 歌曲名
                ar:'',      // 演唱
                al:'',      // 专辑
                by:'',      // 编辑
                list:[],    // 歌词列表
                offset:0    // 时间补偿值 其单位是毫秒
            };

            // 分割歌词行
            lrcLine = lrc.split(/(.*)\n/g);
            lineNumber = lrcLine.length;

            for( var i=0; i<lineNumber; i++ )
            {
                /* 循环一次 一条歌词 */
                lrcLineTime = [];
                lrcLineText = '';
                var time = 0;

                lrcLineTime = lrcLine[i].match(regexpLineTime);
                lrcLineText = lrcLine[i].match(regexpLineText);
                
                if( lrcLineTime != null )
                {
                    var number = lrcLineTime.length;

                    for( var a=0; a<number; a++ )
                    {
                        lrcLineTimeArr = lrcLineTime[a].match(regexpLineTimeArr);

                        if( typeof(lrcLineTimeArr[4]) != 'undefined')
                        {
                            if(ms)
                                time = Number(lrcLineTimeArr[1])*60 + Number(lrcLineTimeArr[2]) + Number(lrcLineTimeArr[4])/1000;
                            else
                                time = Number(lrcLineTimeArr[1])*60 + Number(lrcLineTimeArr[2]);
                        }
                        else
                            time = Number(lrcLineTimeArr[1])*60 + Number(lrcLineTimeArr[2]);

                        time += (lrcObj.offset/1000);   // 时间补偿值
                        
                        lrcObj.list.push( { "time":time, "text":lrcLineText[1] } ); // 添加到歌词列表
                    }
                }
                else
                {
                    if( lrcLine[i].length > 4 )
                    {
                        /* 收集歌词信息 */
                        var ti      = /\[ti\:(.*)\]/;
                        var ar      = /\[ar\:(.*)\]/;
                        var al      = /\[al\:(.*)\]/;
                        var by      = /\[by\:(.*)\]/;
                        var offset  = /\[offset\:(.*)\]/;

                        if( ti.test(lrcLine[i]) )
                            lrcObj.ti = lrcLine[i].match(ti)[1];            // 歌名
                        else if( ar.test(lrcLine[i]) )
                            lrcObj.ar = lrcLine[i].match(ar)[1];            // 演唱
                        else if( al.test(lrcLine[i]) )
                            lrcObj.al = lrcLine[i].match(al)[1];            // 专辑
                        else if( by.test(lrcLine[i]) )
                            lrcObj.by = lrcLine[i].match(by)[1];            // lrc制作者
                        else if( offset.test(lrcLine[i]) )
                            lrcObj.offset = lrcLine[i].match(offset)[1];    // 时间补偿值
                    }
                }
            }
            // 歌词时间排序
            lrcObj.list.sort( function(e, x){ return (e.time-x.time); } );

            // console.log(lrcObj);
            return lrcObj;
        };

        self.play = function()
        {
            self.audio.play();
        };

        self.pause = function()
        {
            self.audio.pause();
        };

        self.prev = function()
        {
            self.$element.find('.cover img').remove();

            if( self.runtime.album.active > -1 )
            {
                self.runtime.album.last = self.runtime.album.index;

                var album = getAlbumList( self.runtime.album.active );
                var music = Storage.getJson( 'Hmusic_' + album.id );
                var index = self.runtime.music.index - 1;

                self.runtime.music.last = self.runtime.music.index;
                if( index > -1 )
                    self.runtime.music.index = index;
                else
                    self.runtime.music.index = music.length - 1;
                
                self.updateMusic();
            }
            else
                self.randomMusic();

            self.play();
        };

        self.next = function()
        {
            self.$element.find('.cover img').remove();

            if( self.runtime.album.active > -1 )
            {
                self.runtime.album.last = self.runtime.album.index;

                var album = getAlbumList( self.runtime.album.active );
                var music = Storage.getJson( 'Hmusic_' + album.id );
                var index = self.runtime.music.index + 1;

                self.runtime.music.last = self.runtime.music.index;

                if( index < music.length )
                    self.runtime.music.index = index;
                else
                    self.runtime.music.index = 0;

                self.updateMusic();
            }
            else
                self.randomMusic();
            
            self.play();
        };

        self.random = function()
        {
            self.$element.find('.cover img').remove();

            self.randomMusic();
            self.play();
        };

        self.src = function( src )
        {
            if( typeof src == 'undefined' )
                return self.audio.src;
            else
            {
                self.pause();
                self.audio.src = src;
            }
        };

        /* 添加列表 */
        self.addItem = function( list, type )
        {
            // type 1=歌曲  2=专辑
            var type = arguments[1] ? arguments[1]:1;
            var li = [];
            var content = '';

            if( list.length > 0 )
            {
                $.each( list, function( key, value )
                {
                    var item = '';

                    if( value.active )
                        item = '<li class="active">';
                    else
                        item = '<li>';
                    
                    if( type == 2 )
                        item += '<i class="fa fa-angle-right"></i>';

                    item += '<span class="list-taxis">' + (key+1) + '</span>';

                    if( type == 2 )
                        item += '<span class="status"></span>';

                    if( type == 2 )
                    {
                        if( value.description )
                            item += '<span class="list-name">' + value.title + ' - ' + value.description + '</span>';
                        else
                            item += '<span class="list-name">' + value.title + '</span>';
                    }
                    else
                    {
                        if( value.author )
                            item += '<span class="list-name">' + value.title + ' - ' + value.author + '</span>';
                        else
                            item += '<span class="list-name">' + value.title + '</span>';
                    }

                    item += '</li>';
                    li.push(item);
                });

                content = '<ul>' + li.join('') + '</ul>';

                if( type == 2 )
                {
                    self.$element.find('.list-album .block-content').html( content );
                    self.$element.find('.list-album .block-content').mCustomScrollbar({mouseWheelPixels:200});
                }
                else
                {
                    self.$element.find('.list-music .block-content').html( content );
                    self.$element.find('.list-music .block-content').mCustomScrollbar({mouseWheelPixels:200});
                }
            }
            else
                self.$element.find('.list-music .block-content').html( '' );
        };

        /* 加载动画 */
        function loading()
        {
            var content = '<div class="spinner"><div class="double-bounce1"></div><div class="double-bounce2"></div></div>';
            return content;
        }

        /* 加载失败 */
        function loadError()
        {

        };

        // 加载歌词
        function loadLrc( list )
        {
            if( typeof list == 'object' && list.length > 1 )
            {
                var li = [];
                li.push( '<ul>' );

                for( var i = 0; i < list.length; i++ )
                {
                    if( list[i].text.length > 2 )
                        li.push( '<li class="base">' + list[i].text + '</li>' );
                    else
                        li.push( '<li class="base">...</li>' );
                }
                
                li.push( '</ul>' );

                $('.Hmusic-lrc').html( li.join('') );
                $('.Hmusic-lrc ul li').eq(0).addClass( 'current' );

                self.runtime.lrc = list;
                $.HmusicTips( '歌词加载成功..' );
            }
            else
            {
                self.runtime.lrc = false;
                $.HmusicTips( '歌词加载失败..' );
            }
        };

        /**
         * 显示歌曲列表
         * @param  {[type]} id 专辑ID
         * @return {[type]}    [description]
         */
        function showMusicList( album_id )
        {
            var row = Storage.has( 'Hmusic_' + album_id );
            if( !row )
            {
                HTTP.request( '/Music/lists/album_id/' + album_id, 'get', null, function( res ){
                        if( res.code == 0 )
                        {
                            Storage.setJson( 'Hmusic_' + album_id, res.value );
                            self.addItem( res.value, 1 );
                        }
                        else
                            self.$element.find('.list-music .block-content').html( loading() );
                    }
                );
            }
            else
            {
                var list = Storage.getJson( 'Hmusic_' + album_id );
                self.addItem( list, 1 );
            }
        }

        /* 获取歌曲信息 */
        function getMusicDetil( index )
        {
            var albumDetail = getAlbumList(self.runtime.album.active);
            console.log(albumDetail);

            var musicList = Storage.getJson( 'Hmusic_' + albumDetail.id );
            console.log(musicList[index]);
            
            return musicList[index];
        };

        /* 更新歌词显示位置 */
        self.updateLrc = function()
        {
            if( typeof(self.runtime.lrc) == 'object' && self.runtime.lrc.length > 0 )
            {
                var length = self.runtime.lrc.length;
                var currentTime = self.audio.currentTime;
                line = $('.Hmusic-lrc .current').index();

                for( var i=0; i<length; i++ )
                {
                    if( currentTime > self.runtime.lrc[i].time && ( typeof(self.runtime.lrc[i+1]) == 'undefined' || currentTime < self.runtime.lrc[i+1].time) )
                    {
                        if( line != i )
                        {
                            var top = i * 50;
                            $('.Hmusic-lrc ul').css( { top: '-' + top + 'px' } );
                            $('.Hmusic-lrc .current').removeClass( 'current' );
                            $('.Hmusic-lrc li').eq( i ).addClass( 'current' );
                            break;
                        }
                    }
                }
            }
        }

        // 加载音乐
        self.updateMusic = function()
        {
            // 去除歌词
            self.runtime.lrc = false;
            $('.Hmusic-lrc').html( '<ul><li class="base">Hmusic 音乐播放器</li></ul>' );

            // 取消上次播放专辑歌曲列表的状态
            if( self.runtime.album.last > -1 && (self.runtime.album.last != self.runtime.album.active) )
            {
                var album = getAlbumList(self.runtime.album.last);
                var musicList = Storage.getJson( 'Hmusic_' + album.id );

                for( var i=0; i<musicList.length; i++ )
                    musicList[i].active = false;

                Storage.setJson( 'Hmusic_' + album.id , musicList );
            }

            // 取消当前专辑状态
            var album = getAlbumList( self.runtime.album.active );
            var musicList = Storage.getJson( 'Hmusic_' + album.id );
            for( var i=0; i<musicList.length; i++ )
                musicList[i].active = false;
            Storage.setJson( 'Hmusic_' + album.id , musicList );

            // 设置当前播放歌曲状态
            var album = getAlbumList( self.runtime.album.active );
            var music = Storage.getJson( 'Hmusic_' + album.id );
            music[self.runtime.music.index].active = true;
            Storage.setJson( 'Hmusic_' + album.id, music );

            // 设置 歌曲信息
            var albumDetail = getAlbumList(self.runtime.album.active); // 获取全部专辑
            // 歌曲列表
            var musicList = Storage.getJson( 'Hmusic_' + albumDetail.id );

            self.$element.find('.arguments-name').text( musicList[self.runtime.music.index].title ); // 歌曲名称
            self.$element.find('.arguments-author').text( musicList[self.runtime.music.index].author ); // 歌曲演唱
            self.$element.find('.arguments-special').text( musicList[self.runtime.music.index].album ); // 专辑

            self.$element.find('.cover').addClass('changing');
            if( musicList[self.runtime.music.index].picbig.length > 5 )
            {
                loadImage( musicList[self.runtime.music.index].picbig, function( obj ){
                    self.$element.find('.cover').html( obj );
                    setTimeout( function(){ self.$element.find('.cover').removeClass('changing'); }, 100 );
                }, function( obj ){
                    $.HmusicTips( '图片加载失败..' );
                });
            }

            self.audio.src = musicList[self.runtime.music.index].src;
            
            // 加载歌词
            HTTP.request( musicList[self.runtime.music.index].lrc, 'get', null, function( res ){
                if( res.code == 0 )
                {
                    var data = res.value;
                    if( typeof(data.lrc) != null )
                    {
                        var lrcObj = self.analysisLrc( data.lrc );
                        loadLrc( lrcObj.list );
                    }
                    else
                    {
                        self.runtime.lrc = false;
                        $.HmusicTips( '歌词加载失败..' );
                    }
                }
            }, null, true, true, 2 );

            // 设置歌曲列表的 UI显示
            if( self.runtime.album.index == self.runtime.album.active )
            {
                self.$element.find('.list-music li').removeClass('active');
                self.$element.find('.list-music li').eq(self.runtime.music.index).addClass('active');
            }
            console.log( 'Hmusic - 当前播放：' + musicList[self.runtime.music.index].title + ' - ' + musicList[self.runtime.music.index].author );
            $.HmusicTips( '歌曲加载成功..' );
        };

        // 随机选中歌曲
        self.randomMusic = function()
        {
            if( self.runtime.album.active > -1 )
            {
                self.runtime.album.last = self.runtime.album.index;

                var album = getAlbumList( self.runtime.album.active );
                var musicList = Storage.getJson( 'Hmusic_' + album.id );
                var randomM = randoms( 0, musicList.length-1 );

                self.runtime.music.last = self.runtime.music.index;
                self.runtime.music.index = randomM;

                // 更新歌曲信息
                self.updateMusic();
            }
        };

        /* 获取专辑列表 或 专辑详情 */
        function getAlbumList( index )
        {
            if( !Storage.has('album') )
            {
                HTTP.request( '/Album/lists', 'get', null, function( res ){
                    if( res.code == 0 )
                    {
                        Storage.setJson( 'album', res.value );
                        self.$element.find('.list-album .block-title .number').text( res.value.length );
                    }
                });
            }

            var album = Storage.getJson('album');

            if( typeof index != 'undefined' )
                return album[index];

            return album;
        };

        /* 获取歌曲长度 秒 */
        self.duration = function()
        {
            return self.audio.duration;
        };

        self.setAlbumTitle = function( title ){
            self.$element.find('.list-album .block-title .title').html( title );
        };

        self.listenEvent( 'play', EventPlay );
        self.listenEvent( 'pause', EventPause );
        self.listenEvent( 'ended', EventEnded );
        self.listenEvent( 'timeupdate', EventTimeupdate );
        self.listenEvent( 'loadedmetadata', EventLoadedmetadata );
        self.listenEvent( 'loadstart', EventLoadstart );
        // self.listenEvent( 'loadedmetadata', EventLoadedmetadata );
        
        /* 开始 */
        function EventPlay( e )
        {
            self.$element.find('.control-status>i').addClass('active');
            self.$element.find('.cover').addClass('animation-roate');
            self.$element.find('.flat').addClass('active');

            // 修改专辑显示状态
            self.$element.find('.list-album .active').find('.status').html( '' );
            self.$element.find('.list-album .active').removeClass('active');
            self.$element.find('.list-album li').eq(self.runtime.album.active).addClass('active');
            self.$element.find('.list-album .active>.status').html('正在播放 &gt; ');
            
            $.HmusicTips( '开始播放..' );
        }
    
        /* 暂停 */
        function EventPause( e )
        {
            self.$element.find('.control-status>i').removeClass('active');
            self.$element.find('.cover').removeClass('animation-roate');
            self.$element.find('.flat').removeClass('active');

            if( self.runtime.album.active > -1 )
                self.$element.find('.list-album .active>.status').html('暂停播放 &gt; ');

            $.HmusicTips( '暂停播放..' );
        }

        /* 播放结束 */
        function EventEnded( e )
        {
            self.$element.find('.control-status>i').removeClass('active');
            self.$element.find('.cover').removeClass('animation-roate');

            // 去除歌词
            self.runtime.lrc = false;
            $('.Hmusic-lrc').html( '<ul><li class="base">Hmusic 音乐播放器</li></ul>' );

            console.log( '模式：' + self.options.model );
            
            if( self.options.model == 1 ) // 列表
                self.next();
            else if( self.options.model == 2 ) // 随机
                self.random();
            else if( self.options.model == 3 ) // 单曲
            {
                self.updateMusic();
                self.play();
            }
        }

        /* 播放时间改变 */
        function EventTimeupdate( evt )
        {
            if( self.audio.currentTime < self.audio.duration )
            {
                /* 播放进度条 */
                var nowBar = self.audio.currentTime / self.audio.duration * 100;
                self.$element.find('.arguments-time').text( self.audio.time_s2m( Math.floor(self.audio.currentTime) ) );
                self.$element.find('.progress-bar .active').width( nowBar.toFixed(2) + '%' );
            }
            else if( self.audio.currentTime >= self.audio.duration )
            {
                self.$element.find('.arguments-time').text('00:00');
                self.$element.find('.arguments-total').text('00:00');
                self.$element.find('.progress-bar .active').width(0);

                console.log('播放结束');
            }

            //  歌词开关
            if( self.options.openLrc == 1 )
                self.updateLrc();
        }

        /* 获取资源长度 */
        function EventLoadedmetadata()
        {
            var time = self.audio.time_s2m(Math.floor(self.audio.duration));
            self.$element.find('.arguments-total').text(time);
        }

        /* 开始请求数据 */
        function EventLoadstart( e )
        {
            // console.log('开始请求数据..');
        }

        // 播放按钮透明效果
        self.$element.find('.cover').hover(
            function(){
                self.$element.find('.control-status').css('opacity','0.8');
            },
            function(){
                self.$element.find('.control-status').css('opacity','0.2');
            }
        );

        /* 播放按钮 */
        self.$element.find('.control-status').click(function()
        {
            if( self.audio.paused )
                self.play();
            else
                self.pause();
        });

        /* 上一首 */
        self.$element.find('.control-prev').click(function(){
            self.prev();
        });

        /* 下一首 */
        self.$element.find('.control-next').click(function(){
            self.next();
        });

        /* 控制栏 - 模式切换 */
        self.$element.find('.control-loop').click(function()
        {
            var icon  = '';
            var title = '';
            var nextIcon  = '';
            var nextTitle = '';

            switch( self.options.model )
            {
                case 1: // 列表循环
                    icon  = 'fa-exchange';
                    title = '列表循环';

                    model     = 2; 
                    nextIcon  = 'fa-random';
                    nextTitle = '随机播放';
                    break;
                case 2: // 随机播放
                    icon = 'fa-random';
                    title = '随机播放';

                    model     = 3; 
                    nextIcon  = 'fa-retweet';
                    nextTitle = '单曲循环';
                    break;
                case 3: // 单曲循环
                    icon = 'fa-retweet';
                    title = '单曲循环';

                    model     = 1; 
                    nextIcon  = 'fa-exchange';
                    nextTitle = '列表循环';
                    break;
            }

            self.options.model = model;
            $(this).removeClass(icon);
            $(this).addClass(nextIcon);
            $(this).attr('title',nextTitle);

            self.$element.find('.arguments-type').prev().removeClass(icon);
            self.$element.find('.arguments-type').prev().addClass(nextIcon);
            self.$element.find('.arguments-type').text(nextTitle);
        });

        /* 控制栏 - 喜欢按钮 */
        self.$element.find('.control-heart').click(function()
        {
            $(this).toggleClass('active');
        });

        /* 底部 - 列表按钮 */
        self.$element.find('#btn-music-list').click(function()
        {
            var has = $(this).hasClass('active');

            if( has )
            {
                $(this).removeClass('active');
                $('.an-list').removeClass('active');
                // $('.an-list .list-block').removeClass('active');
            }
            else
            {
                $(this).addClass('active');
                $('.an-list').addClass('active');
                // $('.an-list .list-block').addClass('active');
            }
        });

        /* 底部 - 歌词开关 */
        self.$element.find('#btn-lrc').click(function()
        {
            var has = $(this).hasClass('active');

            if( has )
            {
                self.options.openLrc = 0;
                $(this).addClass('fa-toggle-off');
                $(this).removeClass('fa-toggle-on');
                $(this).removeClass('active');
                $('.Hmusic-lrc').removeClass('active');
            }
            else
            {
                self.options.openLrc = 1;
                $(this).removeClass('fa-toggle-off');
                $(this).addClass('fa-toggle-on');
                $(this).addClass('active');
                $('.Hmusic-lrc').addClass('active');
            }
        });

        /* 底部 - 音量条 */
        self.$element.find('.volume-bar').click(function(evt){
            var offset_left = $(this).offset().left;
            var left = evt.pageX - offset_left;
            self.audio.volume = (left/145).toFixed(2);
            $(this).find('.progress-bg').width( left );
            if( left < 70 )
            {
                self.$element.find('.btn-trumpet').addClass('fa-volume-down');
                self.$element.find('.btn-trumpet').removeClass('fa-volume-up');
            }
            else
            {
                self.$element.find('.btn-trumpet').addClass('fa-volume-up');
                self.$element.find('.btn-trumpet').removeClass('fa-volume-down');
            }
        });

        /* 底部 - 拖到音量按钮 - 按下 */
        self.$element.find('.volume-bar .drag').mousedown(function()
        {
            var dragEnter = false;
            var me = $(this);

            $(document).on( 'mousemove', function(evt){
                dragEnter = true;
                me.addClass('active');
                document.onselectstart = function(){event.returnValue=false;}

                var offset_left = self.$element.find('.volume-bar').offset().left;
                var left = evt.pageX - offset_left;
                if( left > -1 && left < 146 )
                {
                    self.audio.volume = left/145;
                    self.$element.find('.volume-bar .progress-bg').width( left );

                    if( self.$element.find('.btn-trumpet').hasClass('fa-volume-off') )
                        self.$element.find('.btn-trumpet').removeClass('fa-volume-off');

                    if( left < 70 )
                    {
                        self.$element.find('.btn-trumpet').addClass('fa-volume-down');
                        self.$element.find('.btn-trumpet').removeClass('fa-volume-up');
                    }
                    else
                    {
                        self.$element.find('.btn-trumpet').addClass('fa-volume-up');
                        self.$element.find('.btn-trumpet').removeClass('fa-volume-down');
                    }
                }
                else if( left <= 0 )
                {
                    self.audio.volume = 0;
                    self.$element.find('.volume-bar .progress-bg').width( 0 );

                    self.$element.find('.btn-trumpet').removeClass('fa-volume-up');
                    self.$element.find('.btn-trumpet').removeClass('fa-volume-down');
                    self.$element.find('.btn-trumpet').addClass('fa-volume-off');    
                }
                else if( left >= 145 )
                {
                    self.audio.volume = 1;
                    self.$element.find('.volume-bar .progress-bg').width( 145 );
                }
            });

            $(document).mouseup(function(){
                if( dragEnter == true )
                {
                    dragEnter = false;
                    me.removeClass('active');
                    $(document).off( 'mousemove' );
                    document.onselectstart = function(){ return true; };
                    self.$element[0].onselectstart = function(){ return false; };
                }
            });
        });

        /* 点击 - 进度条 */
        self.$element.find('.progress-bar').click(function(e)
        {
            var nowlong = self.audio.duration / 365 * e.offsetX;

            console.log( self.audio.readyState );

            if( self.audio.src )
            {
                self.audio.currentTime = nowlong;
            }
        });

        /* 侧边收缩按钮 */
        self.$element.find('.an-side').click(function()
        {
            var has = self.$element.find('.an-side>i').hasClass('active');
            if( has )
            {
                // 收缩
                self.$element.find('.an-side>i').removeClass('active');
                self.$element.removeClass('active');
            }
            else
            {
                // 伸展
                self.$element.find('.an-side>i').addClass('active');
                self.$element.addClass('active');
            }
        });

        /* 列表 - 点击专辑 */
        self.$element.find('.list-album').delegate( 'li', 'click', function()
        {
            self.$element.find('.list-album').removeClass('active');
            self.$element.find('.list-music').addClass('active');

            var index = $(this).index();
            self.runtime.album.index = index;

            $('.list-music .block-content').html( loading() );

            var item = getAlbumList( index ); // 当前专辑
            showMusicList( item.id ); // 获取歌曲列表
        });

        /* 歌曲列表 - 播放 */
        self.$element.find('.list-music').delegate( 'li', 'click', function(evt)
        {
            var index = $(this).index();

            self.runtime.album.last = self.runtime.album.active;
            self.runtime.album.active = self.runtime.album.index;
            self.runtime.music.last = self.runtime.music.index;
            self.runtime.music.index = index;

            self.updateMusic();
            self.play();
        });

        /* 歌曲列表 - 返回 */
        self.$element.find('.list-music>.block-title').click( function()
        {
            self.$element.find('.list-music').removeClass('active');
            self.$element.find('.list-album').addClass('active');
        });

        // 初始化
        self.init = function()
        {
            HTTP.request( '/Album/lists', 'get', null, function( res ){
                if( res.code == 0 )
                {
                    var album = res.value;
                    self.$element.find('.list-album .block-title .number').text( album.length );
                    Storage.setJson( 'album', album );
                    self.addItem( album, 2 );

                    for( var i=0; i<album.length; i++ )
                    {
                        if( album[i].defaults == 1 )
                        {
                            self.runtime.album.last = self.runtime.album.active;
                            self.runtime.album.active = i;
                            var params = { album_id:album[i].id };
                            HTTP.request( '/Music/lists', 'get', params, function( data ){
                                if( data.code == 0 ){
                                    Storage.setJson( 'Hmusic_' + params.album_id, data.value );
                                    self.randomMusic();
                                    $.HmusicTips( '播放器初始化成功..' );
                                }
                            }, function( res ){
                                $.HmusicTips( '播放器初始化失败..' );
                            });
                        }
                    }
                }
            });
        };

        self.init();
        return self;
    };

    $.extend({
        Hmusic:function( options )
        {
            Storage.removeKeys('Hmusic_');
            var content = [];
            content.push( '<div id=Hmusic class=Hmusic-base><div class=an-panel><div class=parameter><div class=parameter-other><div class=left><i class="fa fa-music"></i><span class=arguments-name>加载...</span></div><div class=right><i class="fa fa-clock-o"></i><span class=arguments-time>00:00</span>/<span class=arguments-total>00:00</span></div></div><div class=parameter-other><div class=left><i class="fa fa-user"></i><span class=arguments-author>加载...</span></div><div class=right><i class="fa fa-exchange"></i><span class=arguments-type>列表循环</span></div></div><div class=parameter-other><div class=left><i class="fa fa-folder"></i><span class=arguments-special>加载...</span></div><div class=right><i class="fa fa-check-circle"></i><span class=arguments-lrc>歌词开启</span></div></div></div><div class=cover><img src=image/avatar.jpg></div><div class=control><i class="control-loop fa fa-exchange" title="列表循环"></i><i class="control-prev fa fa-backward" title="上一首"></i><div class=control-status><i class="control-play fa fa-play" title="播放"></i><i class="control-pause fa fa-pause" title="暂停"></i></div><i class="control-next fa fa-forward" title="下一首"></i><i class="control-heart fa fa-heart" title="收藏"></i></div><div class=progress-bar><div class=bar><div class=active></div></div></div><div class=bottom><div class=bottom-left><i class="btn-trumpet fa fa-volume-up"></i><div class=volume-bar><div class=progress-bg><div class="volume-on ts5"><div class=drag title="音量"></div></div></div></div></div><div class=bottom-right><div class=btn-list><i class="fa fa-bars" id=btn-music-list title="播放列表"></i></div><div class=btn-list><i class="fa fa-toggle-on active" id=btn-lrc title="歌词开关"></i></div></div></div></div><div class=an-list><div class="list-block list-album active"><div class=block-title><span class=title>Hmusic音乐播放器 - 专辑列表</span>(<span class=number>0</span>)</div><div class=block-content></div></div><div class="list-block list-music"><div class=block-title><i class="fa fa-angle-left"></i><span>Ziiber 的歌曲列表</span></div><div class=block-content></div></div></div><div class=an-side><i class="fa fa-angle-right"></i></div><div class=flat><i class="fa fa-music"></i><i class="fa fa-music"></i><i class="fa fa-music"></i><i class="fa fa-music"></i><i class="fa fa-music"></i><i class="fa fa-music"></i></div></div>' );
            content.push( '<div class="Hmusic-lrc active"><ul><li class="base current">Hmusic 音乐播放器</ul></div>' );
            
            $('body').append( content.join('') );
            
            var hmusic = new Hmusic( $('#Hmusic'), options );
            return hmusic;
        }
    });

 })(jQuery, window);